<?php

namespace addons\mental\controller;

use addons\mental\model\Feedback as feedbackModel;
use app\admin\model\help\Content;
use app\admin\model\help\Main;
use app\admin\model\xlzxinfo\Tags;
use think\Db;
use think\Cache;
use think\Log;

class Help extends Base
{
    protected $noNeedLogin = ['list'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\help\Main;
    }
    
    // public function send_post($token = null,$content = null){
    //     $curl = curl_init();
    //     $openid = Db::name('user')->where('id',$this->auth->id)->value('openid');
    //     curl_setopt_array($curl, array(
    //       CURLOPT_URL => 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token='.$token,
    //       CURLOPT_RETURNTRANSFER => true,
    //       CURLOPT_ENCODING => '',
    //       CURLOPT_MAXREDIRS => 10,
    //       CURLOPT_TIMEOUT => 0,
    //       CURLOPT_FOLLOWLOCATION => true,
    //       CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    //       CURLOPT_CUSTOMREQUEST => 'POST',
    //       CURLOPT_POSTFIELDS =>'{"content":"'.$content.'","version":2,"scene":2,"openid":"'.$openid.'"}',
    //       CURLOPT_HTTPHEADER => array(
    //         'Content-Type: application/json'
    //       ),
    //     ));
        
    //     $response = curl_exec($curl);
        
    //     return $response;
    //     curl_close($curl);
    // }
    /**
     *
     * 发布求助
     * @return void
     */
    public function publish()
    {
        //标题、内容、敏感词验证 program_access_token 小程序token
        $access_token = Cache::get("program_access_token");
        if(!$access_token){
            $appId = 'wx170fe8ce2ce8c283';
            $appSecret = 'ae6c0d43a4f5d6ee537f41136dd01219';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
            $data = json_decode(getJson($url),true);
            Log::info('token:'.json_encode($data,true));
            if(isset($data['access_token']) && $data['access_token'] != ''){
                Cache::rm("program_access_token");
                Cache::set("program_access_token",$data['access_token'],7000);
                $access_token=$data['access_token'];
            }
            Log::info('redis_program:'.$access_token);
        }
        $openid = Db::name('user')->where('id',$this->auth->id)->value('openid');
        $title = $this->request->post('title');
        $des = $this->request->post('des');
        if (!$title || !$des) {
            $this->error('请填写标题/内容');
        }
        $ret = send_post($access_token,$title,$openid);
        $data = json_decode($ret,true);
        if($data['result']['label']!=100){
            $this->error('标题存在敏感信息');
        }
        $ret1 = send_post($access_token,$des,$openid);
        $data1 = json_decode($ret1,true);
        if($data1['result']['label']!=100){
            $this->error('内容存在敏感信息');
        }
        
        $tags = $this->request->post('tags',0);
        $amount = $this->request->post('amount');
        
        $tag_info = Tags::where(['id'=>$tags])->find();
        if (!$tag_info){
            $this->error('标签不存在');
        }
//        if (!is_numeric($amount) || $amount<0){
//            $this->error('请输入正确悬赏金额');
//        }
//        $amount = round($amount,2);
        $amount = 0;
        $user_money = \app\common\model\User::where(['id'=>$this->auth->id])->value('money');

        if ($user_money<$amount){
            $this->error('余额不足');
        }
        // 启动事务
        Db::startTrans();
        try{
            if ($amount>0){
                \app\common\model\User::money(-$amount,$this->auth->id,'发布悬赏',3);
            }
            $MainHelpModel = new Main();
            $MainHelpModel->save([
                'user_id' => $this->auth->id,
                'title' => $title,
                'des' => $des,
                'tags' => $tags,
                'amount' => $amount,
            ]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $this->error(__('Operation failed'));
            // 回滚事务
            Db::rollback();
        }

        $this->success(__('Operation completed'));

    }

    /**
     *
     * 求助列表
     * @return void
     */
    public function list()
    {
        $tags = $this->request->get('tags');
        $user_id = $this->request->get('user_id',0);
        $page = $this->request->get('page',1);
        $pageNumber = $this->request->get('pageNumber',10);
        $keywords = $this->request->get('keywords','');
        $params = $this->request->get();
        if(!isset($params['page']) && empty($params['page'])) $params['page'] = 1;
        if(!isset($params['pageNumber']) && empty($params['pageNumber'])) $params['pageNumber'] = 20;

        $where = [];
        if ($tags){
            $where['tags'] = $tags;
        }
        if ($user_id){
            $where['user_id'] = $user_id;
        }
        if ($keywords){
            $where['title'] = ['LIKE','%'.$keywords.'%'];
        }
        $lsit = $this->model
            ->with(['user','tags'])
            ->where($where)
            ->paginate($pageNumber);
        if ($lsit->total()>0){
            foreach ($lsit->items() as $key=>&$value)
            {
                $value['comment_num'] = Content::where(['main_id'=>$value['id']])->count();
            }
        }

        $this->success('请求成功', $lsit);
    }

    /*
     * 求助详情
     * */
    public function detail()
    {
        $id = $this->request->get('id');

        $data = $this->model
            ->with(['user','tags'])
            ->where(['fa_help_main.id'=>$id])
            ->find();
        if (!$data){
            $this->error('求助不存在');
        }
        $comment = Content::with(['teacher'])->where(['main_id'=>$id])->select();
        $data['comment_num'] = count($comment);
        $data['comment'] = $comment;
        $this->success('请求成功', $data);
    }
    /*
     * 求助评论
     * */
    public function help_comment()
    {
        $id = $this->request->post('id',0);
        $content= $this->request->post('content','');
        $help = $this->model->where(['id'=>$id])->find();
        if (!$help){
            $this->error('求助不存在');
        }
        if (!$content){
            $this->error('请填写内容');
        }
        if ($help['status']==2){
            $this->error('求助已有采纳');
        }
        $xlzxinfo = \app\admin\model\xlzxinfo\Xlzxinfo::where(['user_id'=>$this->auth->id,'status'=>1])->find();
        if (!$xlzxinfo){
            $this->error('不是心理咨询师');
        }
        $has_comment =  Content::where(['main_id'=>$id,'user_id'=>$this->auth->id])->find();
        if ($has_comment){
            $this->error('您已评论过');
        }
        $data = [
            'main_id'=>$id,
            'user_id'=>$this->auth->id,
            'xlzxinfo_id'=>$xlzxinfo['id'],
            'status'=>1,
            'content'=>$content,
            'createtime'=>time(),
        ];
        Content::Create($data);

        $this->success('评论成功',[]);
    }

    /**
     *
     * 采纳求助
     * @return void
     */
    public function accept()
    {
        $id = $this->request->post('id');

        $comment = Content::where(['id'=>$id])->find();
        if (!$comment){
            $this->error('评论不存在');
        }
        $main = Main::where(['id'=>$comment['main_id']])->find();
        if ($main['user_id']!=$this->auth->id){
            $this->error('不是发布人');
        }

        // 启动事务
        Db::startTrans();
        try{

            //给赏金
            // if ($main['amount']>0){
            //     \app\common\model\User::money(+$main['amount'],$comment['user_id'],'求助赏金',4);
            //     \think\Db::name('user')->where('id', $comment['user_id'])->setInc('cumulative_gain',$main['amount']);
            // }
            //更新评论状态
            $comment->status = 2;
            $comment->save();
            //更新求助状态
            $main->status = 2;
            $main->save();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $this->error(__('Operation failed'));
            // 回滚事务
            Db::rollback();
        }

        $this->success(__('Operation completed'));

    }

}
